﻿using AutoMapper;
using BBICMS.Infrastructure.Configs;
using BBICMS.Model.Works;
using BBICMS.Model.ViewModel.Back;
using BBICMS.WebUI.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BBICMS.Application.InputModels.Works;
using BBICMS.Resources;
using BBICMS.Application.ViewModels;

namespace BBICMS.WebUI.Areas.Admin.Controllers
{
    [SIGAuth]
    
    public class WorkController : BaseController
    {
        #region 案例       
     
        
        //
        // GET: /bbi_Admin/workIM/
       
        public ActionResult Index(int? page)
        {

            var workList = new Model.ViewModel.Back.WorkListVM
            {
                Works = _unit.Works.GetAll((w=>w.WorkTypes)).OrderByDescending(s => s.AddedDate),
                PageSize = SettingsManager.Work.PageSize,
                PageNumber = page ?? 1
            };               

            return View(workList);
        }

       
        public ActionResult AddWork()
        {
       
            var vm = new WorkIM()
            {
                Active = true
            };

            var solutions = _unit.Solutions.GetAll().OrderByDescending(c => c.Importance).ToList();
            var lSolutions = new SelectList(solutions, "Id", "Title");
            ViewBag.Solutions = lSolutions;


            var clients = _unit.Clients.GetAll().OrderByDescending(c => c.Importance).ToList();
            var lClients = new SelectList(clients, "Id", "ClientName");
            ViewBag.Clients = lClients;


            ViewBag.Types = _unit.WorkTypes.GetAll().OrderByDescending(t=>t.Importance).ToList();
            return View(vm);
        }


        [HttpPost]
        [ValidateInput(false)]       
        public JsonResult AddWork(WorkIM workIM)
        {
            if (ModelState.IsValid)
            {
                var work = Mapper.Map<Work>(workIM);


                if (workIM.WorkTypesIds != null)
                {
                    var lCategories = (from c in _unit.WorkTypes.GetAll()
                                       where workIM.WorkTypesIds.Contains(c.Id.ToString())
                                       select c).ToList();

                    work.WorkTypes = lCategories;
                    work.TypeIds = string.Join(",", workIM.WorkTypesIds);
                }
                              

                work.KeyWords = work.KeyWords.Replace("，", ",");

                _unit.Works.Add(work);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertCreateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(string.Format(Messages.AlertCreateFailure, EntityNames.Work));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


         public ActionResult EditWork(int id)
        {
            var work = _unit.Works.GetById(id);
            if (work != null)
            {
                var workIM = Mapper.Map<WorkIM>(work);


                var solutions = _unit.Solutions.GetAll().OrderByDescending(c => c.Importance).ToList();
                var lSolutions = new SelectList(solutions, "Id", "Title");
                ViewBag.Solutions = lSolutions;


                var clients = _unit.Clients.GetAll().OrderByDescending(c => c.Importance).ToList();
                var lClients = new SelectList(clients, "Id", "ClientName");
                ViewBag.Clients = lClients;


                ViewBag.Types = _unit.WorkTypes.GetAll().OrderByDescending(t => t.Importance).ToList();

                return View(workIM);
            }

            return View("Index");
        }



        [HttpPost]
        [ValidateInput(false)]
       

        public JsonResult EditWork(WorkIM workIM)
        {

            if (ModelState.IsValid)
            {

               

                //  workIM.Categories = lCategories;

                var existingWork = _unit.Works.GetById(workIM.Id);

                existingWork.SolutionId = workIM.SolutionId;
                existingWork.FinishYear = workIM.FinishYear;
                existingWork.Title = workIM.Title;
                existingWork.ClientId = workIM.ClientId;
                existingWork.Demourl = workIM.Demourl;
                existingWork.Abstract = workIM.Abstract;
                existingWork.Body = workIM.Body;
                existingWork.ImageUrl = workIM.ImageUrl;
                existingWork.KeyWords = workIM.KeyWords.Replace("，", ",");
                existingWork.Thumbnail = workIM.Thumbnail;
                existingWork.Active = workIM.Active;
                existingWork.Recommend = workIM.Recommend;
              

                existingWork.WorkTypes.Clear();

                if (workIM.WorkTypesIds!=null)
                {
                    existingWork.TypeIds = string.Join(",", workIM.WorkTypesIds);
                    var lCategories = (from c in _unit.WorkTypes.GetAll()
                                       where workIM.WorkTypesIds.Contains(c.Id.ToString())
                                       select c).ToList();
                    existingWork.WorkTypes = lCategories;  //分类付值
                }else
                {
                    existingWork.TypeIds = string.Empty;                   
                }
              
           
                _unit.Works.Update(existingWork);
                _unit.SaveChanges();

                AR.SetSuccess(string.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(string.Format(Messages.AlertUpdateFailure, EntityNames.Work));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


         [HttpPost]
         public JsonResult RecommendWork(int id)
         {

             var vWork = _unit.Works.GetById(id);

             try
             {
                 if (vWork != null)
                 {
                     vWork.Recommend = !vWork.Recommend;

                     _unit.Works.Update(vWork);
                     _unit.SaveChanges();
                     
                 }
             }
             catch (Exception ex)
             {
                 return Json(false, JsonRequestBehavior.DenyGet);
             }
             return Json(true, JsonRequestBehavior.DenyGet);              

         }


         // DELETE: /User/DeleteSite
         [HttpPost]
         public JsonResult DeleteWork(int id)
         {

             var vWork = _unit.Works.GetById(id);

             if (vWork != null)
             {
                 //string imgurl = Server.MapPath(vCategory.ImageURL);
                 //if (System.IO.File.Exists(imgurl))
                 //{
                 //    System.IO.File.Delete(imgurl);    //删除缩略图
                 //}

                 _unit.Works.Delete(vWork);
                 _unit.SaveChanges();
                 return Json(true, JsonRequestBehavior.DenyGet);
             }

             return Json(false, JsonRequestBehavior.DenyGet);
         }



        #endregion

        #region 案例分类

        // GET: /bbi_Admin/workIM/Types
       
        public ActionResult Types(int? page)
        {

            IEnumerable<WorkType> WorkList = _unit.WorkTypes.GetAll().OrderByDescending(w => w.Importance).ThenByDescending(w => w.AddedDate);

            return View(WorkList);
        }

       
        public ActionResult AddType()
        {
            WorkType vWorkType = new WorkType();
            vWorkType.Active = true;
            vWorkType.Importance = 0;

            return View("AddType", vWorkType);
        }


        [HttpPost]
       
        public JsonResult AddType(WorkType workType)
        {
            
            if (ModelState.IsValid)
            {
                _unit.WorkTypes.Add(workType);
                _unit.SaveChanges();

                // TempData["message"] = string.Format("{0} 已经保存", site.Title);
                return Json(true, JsonRequestBehavior.DenyGet);
            }
            else
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }
            //   return RedirectToAction("Index");

        }

       
        public ActionResult EditType(int Id)
        {
            var vType = _unit.WorkTypes.GetById(Id);
            if (vType != null)
            {
                return View(vType);
            }
            return View("NotFound");
        }

        [HttpPost]

        public JsonResult EditType(WorkType type)
        {


            //site.UpdatedBy = User.Identity.Name;
            //site.UpdatedDate = DateTime.Now;   

            if (ModelState.IsValid)
            {
                _unit.WorkTypes.Update(type);
                _unit.SaveChanges();
                return Json(true, JsonRequestBehavior.DenyGet);

            }
            else
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }

        }

        // DELETE: /User/DeleteSite
        [HttpDelete]
        public JsonResult DeleteType(int id)
        {

            WorkType vType = _unit.WorkTypes.GetById(id);

            if (vType != null)
            {
                //string imgurl = Server.MapPath(vBlog.ImageURL);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}
                     

                _unit.WorkTypes.Delete(vType);
                _unit.SaveChanges();
                return Json(true, JsonRequestBehavior.DenyGet);
            }

            return Json(false, JsonRequestBehavior.DenyGet);
        }


        #endregion

    }
}
